package goodroommate.ui.platform;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

/**
 * Servlet implementation class MyOperation
 */
@WebServlet("/Test/MyOperation")
public class MyOperation extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyOperation() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String json;
		try (InputStream inputStream = request.getInputStream()) {
			json = IOUtils.toString(inputStream, request.getCharacterEncoding());
		}
		JSONObject jsonObj = JSONObject.fromObject(json);
		MyOperationRequestBean requestBean = (MyOperationRequestBean) JSONObject.toBean(jsonObj, MyOperationRequestBean.class);
		
		int result = requestBean.getOperand1() + requestBean.getOperand2();
		
		MyOperationResponseBean responseBean = new MyOperationResponseBean();
		responseBean.setStatus(0); // success
		responseBean.setResult(result);
		
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		out.print(JSONSerializer.toJSON(responseBean).toString());
	}

}
